// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const account = db.collection("account")
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let dataCal = await account
    .where({ openid: wxContext.OPENID })
    .field({ tili: true, star: true })
    .get()
  let tiliCheck = dataCal.data[0].tili + event.tili
  let starCheck = dataCal.data[0].star + event.star

  if (tiliCheck < 0 || starCheck < 0) {
    return {
      code: 'fail',
      res: null
    }
  }

  await account
    .where({
      openid: wxContext.OPENID
    }).update({
      data: {
        tili: _.inc(event.tili),
        star: _.inc(event.star)
      }
    })

  return {
    code: 'ok',
    res: null
  }
}
